<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/12/30
 * Time: 10:22
 */

namespace common\components\ActionsComponents;
use common\components\DataHelper;
use common\models\Merchant\Merchant;


/**
 * 更新独立操作
 * Class UpdateAction
 * @package common\components\ActionsComponents
 */
class UpdateAction extends CommonAction
{
    public $message = '修改成功!';

    public function run()
    {
        $controller = $this->controller;
        if ( !isset($this->_request[$this->_pk]) ) {
            return $controller->jsonResponse($controller::RESPONSE_FAILURE, "未找到对应的数据");
        }

        $query = null;
        $model = new $this->model();
        $ret = $model->updateByPkCommon($this->_request[$this->_pk], $this->_request, $this->scenarios, $this->condition, $query);
        if ( $ret !== false ) {
            //有可能受影响行数是0 这就不做推送
            if ( $this->isPushLocal && $ret ) {
                DataHelper::local_pull_table(Merchant::getCurrentMerInfo('id'), $model::tableName(), $query[$model::primaryKey()[0]]);
            }

            //成功后回调处理
            if($this->callback instanceof \Closure){
                $fun = $this->callback;
                $fun($this->_request[$this->_pk]);
            }
            return  $controller->jsonResponse($controller::RESPONSE_SUCCESS, $this->message, $this->data);
        }

        return $controller->jsonResponse($controller::RESPONSE_FAILURE, $model->getFirstErrorToStr(), $model->getFirstErrors());
    }
}